const app = new Vue({
    el: '#app',
    data() {
        return {
            userInfo: {
                id: 0,
                user_name: '',
            },
            webSocket: null,
            message: '',
            //chatData: [],
            recordData: [],
            fid: 0,
        }
    },
    methods: {
        init() {
            this.fid = this.getQueryVariable('uid');
            this.getApiToken();
            if (this.access_token !== null) { // 已登录
                this.getUserInfo();
                this.record();
                this.link();
            } else {
                this.$message.error('非法请求！')
            }
        },
        getApiToken() {
            this.access_token = localStorage.getItem('access_token');
        },
        getUserInfo() {
            this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
        },
        link() {
            let _this = this;
            let wsServer = 'ws://127.0.0.1:9502?type=chat_uid_' + this.fid + '&access_token=' + this.access_token;
            let webSocket = new WebSocket(wsServer);

            webSocket.onopen = function (res) {

            };

            webSocket.onmessage = function (res) {
                let data = JSON.parse(res.data)['data'];
                _this.recordData.push({uid: _this.fid, message: data['message']});
            };

            webSocket.onclose = function (res) {
                webSocket.close();
            };

            webSocket.onerror = function (res, e) {
                webSocket.close();
            };

            this.webSocket = webSocket;
        },
        sendMessage() {
            let data = {
                'type': 'chat',
                'uid': this.fid,
                'message': this.message,
            };
            this.webSocket.send(JSON.stringify(data));
            this.recordData.push({uid: this.userInfo.id, message: this.message});
            this.message = '';
        },
        record() {
            axios.get('/chat/record', {
                params: {
                    uid: this.userInfo.id,
                    fid: this.fid,
                }
            }).then(res => {
                if (res.data.code === 1) {
                    this.$message.error(res.data.message);
                    return false;
                }

                this.recordData = res.data.content;
            }).catch(error => {
                this.$message.error(error.message);
                return false;
            });
        },
        getQueryVariable(variable) {
            let query = window.location.search.substring(1);
            let vars = query.split("&");
            for (let i = 0; i < vars.length; i++) {
                let pair = vars[i].split("=");
                if (pair[0] === variable) {
                    return parseInt(pair[1]);
                }
            }
            return 0;
        }
    },
    created() {
        this.init();
    }
});
